package com.irdstudio.efp.esb.api.rest.sed.bmd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.TraceUtil;
import com.irdstudio.efp.cus.service.facade.OrgWhiteListEService;
import com.irdstudio.efp.cus.service.vo.OrgWhiteListEVO;
import com.irdstudio.efp.esb.api.bean.sed.bmd.CorpInfStruct;
import com.irdstudio.efp.esb.api.bean.sed.bmd.ReqSedQueryWhiteBean;
import com.irdstudio.efp.esb.api.bean.sed.bmd.RespSedQueryWhiteBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 渠道白名单企业资格查询
 * 
 * @author weijj
 * @since 2019年4月23日 下午20:03:08
 * @version 1.0
 */

@RestController
@RequestMapping("/esb")
public class NlsQueryWhiteSedController {
	private static Logger logger = LoggerFactory.getLogger(NlsQueryWhiteSedController.class);

	/**
	 * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author weijj
	 * @since 2019年4月22日 下午16:57:08
	 * @version 1.0
	 */
	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("校验 ESB请求系统头和请求应用头对象!");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	/**
	 * 获取ESB请求对象，校验 ESB请求体对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author weijj
	 * @since 2019年4月22日 下午16:57:08
	 * @version 1.0
	 */
	@ModelAttribute("reqSedQueryWhiteBean")
	public ReqSedQueryWhiteBean getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("校验 ESB请求体对象！");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqSedQueryWhiteBean.class);
	}

	/**
	 * 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息<br>
	 * 2.调用对应的中台服务<br>
	 * 3.渠道白名单企业资格查询<br>
	 * 
	 * @param esbReqServiceBean
	 *            ESB请求对象
	 * @param br1
	 * @param reqCreditBean
	 *            ESB请求体的对象
	 * @param br2
	 * @param exception
	 *            切面的异常信息
	 * @return
	 * @throws Exception
	 * @author weijj
	 * @since 2019年4月22日 下午16:57:08
	 * @version 1.0
	 */

	@SuppressWarnings("null")
	@PostMapping("/SERVICE_50130006_01")
	public EsbRespServiceBean doRecv(
            @Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
            @Validated @ModelAttribute("reqSedQueryWhiteBean") ReqSedQueryWhiteBean reqSedQueryWhiteBean,
            BindingResult br2, Exception exception) throws Exception {
		String company_name = reqSedQueryWhiteBean.getWrkCorpNm();// 单位名称
		String pageNo = reqSedQueryWhiteBean.getPgNo();// 页码
		String pageSize = reqSedQueryWhiteBean.getPerPgRcrNum();// 每页显示条数
		String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();// 全局流水号
		String totalSize = null;
		int total = 0;
		List<CorpInfStruct> companyNameArr = new ArrayList<CorpInfStruct>();
		;
		TraceUtil.setTraceId(glblSrlNo);
		logger.info("渠道白名单企业资格查询开始----------单位名称：" + company_name + "------------全局流水号" + glblSrlNo);
		try {
			// 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息
			if (Objects.nonNull(exception)) {
				throw exception;
			}
			OrgWhiteListEVO orgWhiteListEVO = new OrgWhiteListEVO();
			orgWhiteListEVO.setCompanyName(company_name);
			List<OrgWhiteListEVO> companyNameList = orgWhiteListEService.queryOrgWhiteListEByCompanyName(orgWhiteListEVO);
			if (null == companyNameList  || companyNameList.isEmpty()) {
				totalSize = String.valueOf(total);
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "交易成功", totalSize, pageSize, pageNo, companyNameArr)),
						EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "交易成功");
			}

			if (pageNo != null && !"".equals(pageNo) && pageSize != null && !"".equals(pageSize)) {
				total = companyNameList.size(); // 记录总数
				totalSize = String.valueOf(total);
				if (!isInteger(pageNo) || !isInteger(pageSize)) {
					return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
							JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
									"查询失败,但所提供的页码或每页显示条数字段不为整数类型无法显示白名单企业数据", totalSize, pageSize, pageNo,
									companyNameArr)),
							EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
							"查询失败,但所提供的页码或每页显示条数字段不为整数类型无法显示白名单企业数据");
				}
				int pageNo1 = Integer.parseInt(pageNo); // 页码
				int pageSize1 = Integer.parseInt(pageSize); // 每页显示条数
				if (pageNo1 < 1 || pageSize1 < 1) {
					return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
							JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
									"查询失败,但所提供的页码或每页显示条数字段小于1无法显示白名单企业数据", totalSize, pageSize, pageNo,
									companyNameArr)),
							EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
							"查询失败,但所提供的页码或每页显示条数字段小于1每页显示条数不为整数类型无法显示白名单企业数据");
				}
				int pageNoStart = (pageNo1 - 1) * pageSize1; // 每页的起始索引
				if ((pageNo1 - 1) <=  total/pageSize1) {
					if (pageNoStart + pageSize1 > total) {
						companyNameList = companyNameList.subList(pageNoStart, total);
					} else {
						companyNameList = companyNameList.subList(pageNoStart, pageNoStart + pageSize1);
					}
				} else {
					return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
							JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),"交易成功", totalSize, pageSize, pageNo, companyNameArr)),
							EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),"交易成功");
				}
			}
			if (pageNo == null && "".equals(pageNo) && pageSize != null && !"".equals(pageSize)) {
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
								"查询失败,但所提供的页码字段缺少,从而无法显示白名单企业数据", totalSize, pageSize, pageNo, companyNameArr)),
						EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
						"查询失败,但所提供的页码字段缺少,从而无法显示白名单企业数据");
			}

			if (pageNo != null && !"".equals(pageNo) && pageSize == null && "".equals(pageSize)) {
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
								"查询失败,但所提供的每页记录数字段缺少,从而无法显示白名单企业数据", totalSize, pageSize, pageNo, companyNameArr)),
						EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
						"查询失败,但所提供的每页记录数字段缺少,从而无法显示白名单企业数据");
			}
			if (companyNameList != null && !companyNameList.isEmpty()) {
				if (total == 0) {
					total = companyNameList.size();
					totalSize = String.valueOf(total);
				}
				for (OrgWhiteListEVO orgWhiteListEVO2 : companyNameList) {
					CorpInfStruct corpInfStruct = new CorpInfStruct();
					corpInfStruct.setWrkCorpNm(orgWhiteListEVO2.getCompanyName());
					companyNameArr.add(corpInfStruct);
				}
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "查询成功",
								totalSize, pageSize, pageNo, companyNameArr)),
						EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
						"查询成功");
			} else {
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
						JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
								"查询成功,但没有你所查询的白名单企业", totalSize, pageSize, pageNo, companyNameArr)),
						EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
						"查询成功,但没有你所查询的白名单企业");
			}

		} catch (BizException e) {
			logger.error("税e贷渠道白名单企业资格查询接口处理失败!" + e.getMessage());
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
					JSON.toJSONString(buildSedQueryRateBean(EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), e.getMessage(),totalSize, pageSize, pageNo, companyNameArr)),
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.FAILURE.getVALUE(), e.getMessage());
		} catch (Exception e) {
			logger.error("税e贷渠道白名单企业资格查询接口处理失败!" + e.getMessage());
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
					JSON.toJSONString(buildSedQueryRateBean(EsbRetCodeStandard.OTHERS_EXCEPTION.getValue(), e.getMessage(),
							totalSize, pageSize, pageNo, companyNameArr)), 
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbRetCodeStandard.OTHERS_EXCEPTION.getValue(),e.getMessage());
		} finally {
			logger.info("渠道白名单企业资格查询结束----------查询单位名称：" + company_name + "------------全局流水号" + glblSrlNo);
			TraceUtil.clear();
		}

	}

	private RespSedQueryWhiteBean buildSedQueryRateBean(String retStCd, String rtnMsg, String totalSize, String pagSize,
			String pageNo, List<CorpInfStruct> companyNameArr) {
		RespSedQueryWhiteBean respSedQueryWhiteBean = new RespSedQueryWhiteBean();
		respSedQueryWhiteBean.setRetCd(retStCd);
		respSedQueryWhiteBean.setRetMsg(rtnMsg);
		respSedQueryWhiteBean.setCrrspnQryTotCnt(totalSize);
		respSedQueryWhiteBean.setPerPgRcrNum(pagSize);
		respSedQueryWhiteBean.setPgNo(pageNo);
		respSedQueryWhiteBean.setCorpInfStruct(companyNameArr);
		return respSedQueryWhiteBean;
	}

	private boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	@Autowired
	@Qualifier("orgWhiteListEService")
	private OrgWhiteListEService orgWhiteListEService;
}
